<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海口快推科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\api\controller\v1;

use think\Db;
use app\api\logic\v1\ApiLogic;
use app\api\logic\v1\WechatLogic;

class Base extends \app\api\controller\Base
{
    public $appId = 0;

    /**
     * 实例化业务逻辑对象
     */
    public $apiLogic;
    public $wechatLogic;

    /**
     * 系统配置
     */
    public $globalConfig = [];
    public $usersConfig = [];
    public $php_servicemeal = 0;
    /**
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        $dataConf = tpSetting("OpenMinicode.conf");
        $dataConf = json_decode($dataConf, true);
        if (!empty($dataConf['apiopen'])) {
            $this->error('API接口已关闭不可用！');
        } else {
            if (!empty($dataConf['apiverify'])) {
                $times = getTime();
                $apikey_token = input('param.apikey_token/s');
                $arr = explode('-', $apikey_token);
                $request_token = !empty($arr[0]) ? $arr[0] : '';
                $request_time = !empty($arr[1]) ? intval($arr[1]) : 0;
                $new_request_token = md5($request_time.md5($dataConf['apikey']));
                $request_token_arr = [$new_request_token];
                
                /* 修改接口密钥后，小程序发布审核需要一定的时间，旧密钥在7天内继续可用，延期将不可用 start */
                $apikey_uptime = !empty($dataConf['apikey_uptime']) ? intval($dataConf['apikey_uptime']) : 0; // 新密钥修改时间
                $apikey_uptime += (7 * 86400);
                if (!empty($dataConf['old_apikey']) && $apikey_uptime > getTime()) {
                    $old_request_token = md5($request_time.md5($dataConf['old_apikey']));
                    array_push($request_token_arr, $old_request_token);
                }
                /* end */

                if (!in_array($request_token, $request_token_arr)) {
                    $this->error('API请求验证不通过！');
                } else if ($times - $request_time > 300) { // 每个接口时效是5分钟
                    $this->error('当前API请求已过期！');
                }
            }
        }

        $this->appId = input('param.appId/s');
        $this->apiLogic = new ApiLogic;
        $this->wechatLogic = new WechatLogic;
        $this->globalConfig = tpCache('global');
        $this->php_servicemeal = $this->globalConfig['php_servicemeal'];
        $this->usersConfig = getUsersConfigData('all');
    }

    /**
     * 获取当前用户信息
     * @param bool $is_force 是否返回报错提示，还是直接返回值
     * @return UserModel|bool|null
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    protected function getUser($is_force = true)
    {
        $token = $this->request->param('token');
        if (empty($token)) {
            $is_force && $this->error('缺少必要的参数：token', null, ['code'=>-1]);
            return false;
        }

        $users = model('v1.User')->getUser();
        if (empty($users)) {
            $is_force && $this->error('没有找到用户信息', null, ['code'=>-1]);
            return false;
        }

        return $users;
    }

    /**
     * 返回操作成功（附带一些后台配置等数据）
     * @param array $data
     * @param string|array $msg
     * @return array
     */
    protected function renderSuccess($data = [], $msg = 'success', $url = null)
    {
        if (!empty($url) && is_array($data)) {
            $data['url'] = $url;
        }

        // 购物车数量
        $users = $this->getUser(false);
        if (!empty($users['users_id'])) {
            $data['cart_total_num'] = model('v1.Shop')->getCartTotalNum();
        } else {
            $data['cart_total_num'] = 0;
        }

        $data['servicemeal'] = $this->php_servicemeal;

        // 微信公众号APPID(后台-渠道-公众号设置-开发者ID(AppID))
        $config = get_gzh_config();
        $data['appid'] = !empty($config['appid']) ? trim($config['appid']) : '';

        // 获取商城店铺设置信息(后台-设置-店铺信息)
        $data['shopConf'] = model('ShopPublicHandle')->getWebShopConfig($this->usersConfig);

        // 获取商城支付设置信息(后台-设置-支付设置)
        $data['payConfig'] = model('ShopPublicHandle')->getShopPayConfig($this->usersConfig);

        // 注册会员的协议
        $data['usersAgreement'] = Db::name('users_agreement')->where('type', 1)->field('title, content')->find();

        // 商品设置(后台-设置-商城配置)
        $data['goodsConf'] = [
            'goods_unit' => !empty($this->usersConfig['goods_unit']) ? trim($this->usersConfig['goods_unit']) : '',
            'goods_crossed_price' => !empty($this->usersConfig['goods_crossed_price']) ? intval($this->usersConfig['goods_crossed_price']) : 0,
            'goods_stock_warning' => !empty($this->usersConfig['goods_stock_warning']) ? intval($this->usersConfig['goods_stock_warning']) : 0,
        ];

        // 会员设置
        $data['usersConf'] = [
            'shop_open' => empty($this->usersConfig['shop_open']) ? 0 : intval($this->usersConfig['shop_open']),
            'dealer_open' => empty($this->usersConfig['dealer_open']) ? 0 : intval($this->usersConfig['dealer_open']),
            'users_force_login' => empty($this->usersConfig['users_force_login']) ? 0 : intval($this->usersConfig['users_force_login']),
        ];

        // 底部配置
        $data['tabbar'] = Db::name('applets_bottom_nav')->order('sort_order asc')->field('host_id,link_id,nav_title,default_pic,selected_pic')->select();
        if (!empty($data['tabbar'])){
            $this->decorationLogic = new \app\common\logic\DecorationLogic();
            // 获取链接名称
            $data['tabbar'] = $this->decorationLogic->getAdContentLinkNames($data['tabbar']);
            foreach ($data['tabbar'] as $k => $v){
                $v['default_pic'] = handle_subdir_pic($v['default_pic'],'img',true);
                $v['selected_pic'] = handle_subdir_pic($v['selected_pic'],'img',true);
                $data['tabbar'][$k] = $v;
            }
        }

        // 是否存在中转文件
        $data['useTransfer'] = file_exists(DATA_PATH.'conf'.DS.'transfer.txt');

        return $this->result($data, 1, $msg);
    }
    
    /**
     * 返回操作失败
     * @param array $data
     * @param string|array $msg
     * @return array
     */
    protected function renderError($msg = '', $url = null, $data = [], $wait = 1, array $header = [], $target = '_self')
    {
        if (!empty($url) && is_array($data)) {
            $data['url'] = $url;
        }

        return $this->result($data, 0, $msg);
    }

    /**
     * 返回操作成功
     * @param array $data
     * @param string|array $msg
     * @return array
     */
    protected function success($msg = '', $url = null, $data = [], $wait = 1, array $header = [], $target = '_self')
    {
        if (!empty($url) && is_array($data)) {
            $data['url'] = $url;
        }

        return $this->result($data, 1, $msg);
    }

    /**
     * 返回操作失败
     * @param array $data
     * @param string|array $msg
     * @return array
     */
    protected function error($msg = '', $url = null, $data = [], $wait = 1, array $header = [], $target = '_self')
    {
        if (!empty($url) && is_array($data)) {
            $data['url'] = $url;
        }

        return $this->result($data, 0, $msg);
    }
}